package com.pwser.component;

import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.stereotype.Component;

import com.pwser.entities.Menu;
import com.pwser.service.LoginService;

//判定用户请求的url 是否在权限表中，如果在权限表中，则返回给decide方法，用来判定用户是否有此权限。如果不在权限表中则放行
@Component
public class MyFilterInvocationSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {

	@Autowired
	private LoginService loginService;

	private static final int MAP_INIT_SIZE = 5;

	private Map<String, Collection<ConfigAttribute>> menuMap = null;

	//加载所有权限(菜单)
	public void loadResourceDefine() {
		menuMap = new HashMap<>(MAP_INIT_SIZE);
		List<Menu> menus = loginService.getAllMenus();
		for (Menu menu : menus) {
			if (menuMap.containsKey(menu.getUrl())) {
				Collection<ConfigAttribute> configAttributeList = menuMap.get(menu.getUrl());
				ConfigAttribute cfg = new SecurityConfig(menu.getRoleNo());
				configAttributeList.add(cfg);
			} else {
				Collection<ConfigAttribute> configAttributeList = new LinkedList<>();
				ConfigAttribute cfg = new SecurityConfig(menu.getRoleNo());
				configAttributeList.add(cfg);
				menuMap.put(menu.getUrl(), configAttributeList);
			}
		}
	}

	//为了判定用户请求的url 是否在权限表中，如果在权限表中，则返回给decide方法，用来判定用户是否有此权限。如果不在权限表中则放行。
	@Override
	public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
		//加载所有权限
		loadResourceDefine();
		//object 中包含用户请求的request信息
		HttpServletRequest request = ((FilterInvocation) object).getHttpRequest();
//		System.out.println("当前访问路径："+request.getRequestURL());
		Iterator<String> iterator = menuMap.keySet().iterator();
		while (iterator.hasNext()) {
			String url = iterator.next();
			AntPathRequestMatcher matcher = new AntPathRequestMatcher(url);
			if (matcher.matches(request)) {
				return menuMap.get(url);
			}
		}
		return null;
	}

	@Override
	public Collection<ConfigAttribute> getAllConfigAttributes() {
		return null;
	}

	@Override
	public boolean supports(Class<?> clazz) {
		return true;
	}

}
